package at.fhooe.obd.tasks;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import at.fhooe.obd.gui.ChooseTrackActivity;
import at.fhooe.obd.gui.Keys;

public class GetTracksForUserTask extends AsyncTask<Object, Integer, JSONObject> {
	private static final String URL = "http://obdproject.hostoi.com/requestUser.php?userID=";
	private static final String USER_ID = "1";

	boolean testMode = false;
	private static final String TAG = "OBD_Client";
	private Context context;

	@Override
	protected JSONObject doInBackground(Object... params) {
		this.context = (Context) params[0];
		String param = (String) params[1];

		if (testMode) {
			Log.i(TAG, param);

			// create dummy data
			String dummy = "{" + "\"tracks\" : [" + "{" + "\"id\" : 1, " + "\"date\" : \"2012-26-11\", " + "\"user\" : {" + "\"userID\" : 1337, "
					+ "\"userName\" : \"Test-User\" " + "}," + "\"car\" : {" + "\"carID\" : 123," + "\"carName\" : \"BMW 3\", " + "\"carHorsePower\" : 120 "
					+ "}" + "}," + "{" + "\"id\" : 2, " + "\"date\" : \"2012-27-11\", " + "\"user\" : {" + "\"userID\" : 1337, "
					+ "\"userName\" : \"Test-User\" " + "}," + "\"car\" : {" + "\"carID\" : 123," + "\"carName\" : \"BMW 3\", " + "\"carHorsePower\" : 120 "
					+ "}" + "}" + "]" + "}";

			JSONObject obj = null;

			try {
				obj = new JSONObject(dummy);
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return obj;

		} else {
			// TODO user ID should not be static :)
			String json = JsonDownloadHelper.downloadJson(URL, USER_ID);
			JSONObject obj = null;

			try {
				obj = new JSONObject(json);
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return obj;
		}
	}

	@Override
	protected void onPostExecute(JSONObject result) {
		try {
			JSONArray trackArray = new JSONArray(result.get(Keys.JSON_TRACKS).toString());
			String[] processedTracks = new String[trackArray.length()];

			for (int i = 0; i < trackArray.length(); i++) {
				JSONObject jsonObject = trackArray.getJSONObject(i);

				String trackString = "Track Nr. " + jsonObject.getInt(Keys.JSON_ID);
				trackString += " from " + jsonObject.getString(Keys.JSON_DATE);
				processedTracks[i] = trackString;
			}

			if (testMode) {
				for (String s : processedTracks) {
					Log.i(TAG, s);
				}
			}

			// ChooseTrackActivity chooseTrackActivity = new
			// ChooseTrackActivity();

			Intent intent = new Intent(context, ChooseTrackActivity.class);
			intent.putExtra("processedTracks", processedTracks);
			context.startActivity(intent);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// TODO Auto-generated method stub
		super.onPostExecute(result);
	}

}
